#include "SettingsArea.h"
#include "FileManager.h"
#include "PathSettings.h"
#include "Similarity.h"
#include <QDir>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QScrollBar>
#include <QTimer>
#include <QVBoxLayout>

SettingsArea::SettingsArea(QWidget *parent) : QWidget(parent)
{
    // 首先初始化必要的成员变量
    m_facePreviewLabel   = nullptr; // 确保初始为nullptr
    m_faceSelectComboBox = nullptr;
    m_pathSettings       = nullptr;

    try
    {
        // 按顺序初始化组件
        m_pathSettings = new PathSettings(this);

        // 设置UI
        setupUI();

        // 连接信号
        connectSignals();

        // 最后再更新人脸列表
        QTimer::singleShot(0, this,
                           [this]()
                           {
                               // 在事件循环的下一个时间点执行updateFaceList
                               safeUpdateFaceList();
                           });
    }
    catch (const std::exception &e)
    {
        qDebug() << "SettingsArea initialization error:" << e.what();
    }
    catch (...)
    {
        qDebug() << "SettingsArea unknown initialization error";
    }
}

// 添加新的安全更新函数
void SettingsArea::safeUpdateFaceList()
{
    if (!m_pathSettings || !m_faceSelectComboBox || !m_facePreviewLabel)
    {
        qDebug() << "Required components not initialized";
        return;
    }

    try
    {
        QString knownFacesDir = m_pathSettings->getKnownFacesDir();

        // 如果目录路径为空，直接返回
        if (knownFacesDir.isEmpty())
        {
            if (m_facePreviewLabel)
            {
                m_facePreviewLabel->setText("未设置人脸目录");
            }
            return;
        }

        // 检查目录是否存在
        QDir dir(knownFacesDir);
        if (!dir.exists())
        {
            if (m_facePreviewLabel)
            {
                m_facePreviewLabel->setText("人脸目录不存在");
            }
            return;
        }

        // 现在可以安全地调用updateFaceList
        updateFaceList();
    }
    catch (const std::exception &e)
    {
        qDebug() << "Safe update face list error:" << e.what();
        if (m_facePreviewLabel)
        {
            m_facePreviewLabel->setText("更新人脸列表失败");
        }
    }
    catch (...)
    {
        qDebug() << "Unknown error in safe update face list";
        if (m_facePreviewLabel)
        {
            m_facePreviewLabel->setText("更新失败");
        }
    }
}

void SettingsArea::setupUI()
{
    // 首先创建所有控件
    m_modifyPathButton            = new QPushButton("修改文件路径", this);
    m_settingsButton              = new QPushButton("AI服务设置", this);
    m_clearAndScanFolderButton    = new QPushButton("全部重新扫描", this);
    m_appendScanFolderButton      = new QPushButton("新增更新扫描", this);
    m_rescanFolderButton          = new QPushButton("重新扫描文件", this);
    m_recognizeAllFacesButton     = new QPushButton("重新扫描人脸", this);
    m_recognizeFacesButton        = new QPushButton("重新识别人脸", this);
    m_regenerateTypeButton        = new QPushButton("重新生成类型", this);
    m_regenerateDescriptionButton = new QPushButton("重新生成描述", this);
    m_regenerateEmbeddingButton   = new QPushButton("重新生成嵌入向量", this);
    m_refreshFaceListButton       = new QPushButton("刷新人脸列表", this);

    m_contentSearchInput          = new QLineEdit(this);
    m_contentSearchButton         = new QPushButton("查找", this);
    m_contentSearchResultsSpinBox = new QSpinBox(this);
    m_contentSearchResultsSpinBox->setMinimum(1);
    m_contentSearchResultsSpinBox->setMaximum(1000000);
    m_contentSearchResultsSpinBox->setValue(9);
    m_contentSearchResultsSpinBox->setPrefix("显示前 ");
    m_contentSearchResultsSpinBox->setSuffix(" 张");

    m_imagePreviewLabel = new QLabel(this);
    m_imagePreviewLabel->setFixedSize(100, 100);
    m_imagePreviewLabel->setScaledContents(true);
    m_imagePreviewLabel->setAlignment(Qt::AlignCenter);
    m_imagePreviewLabel->setText("未选择图片");
    m_imageSearchSelectButton = new QPushButton("选择图片", this);
    m_imageSearchButton       = new QPushButton("以图搜图", this);

    m_typeSearchInput    = new QLineEdit(this);
    m_typeSearchButton   = new QPushButton("查找", this);
    m_typeSelectComboBox = new QComboBox(this);
    m_typeSelectComboBox->addItems({"人物", "文本", "合照", "自拍", "风景", "植物", "食物", "建筑",
                                    "动物", "电子产品", "证件", "广告", "截图", "网页", "玩具",
                                    "家具", "其他"});
    m_typeSelectButton = new QPushButton("查找", this);

    m_faceSearchInput    = new QLineEdit(this);
    m_faceSearchButton   = new QPushButton("查找", this);
    m_faceSelectComboBox = new QComboBox(this);
    m_faceSelectButton   = new QPushButton("查找", this);

    m_keywordSearchInput  = new QLineEdit(this);
    m_keywordSearchButton = new QPushButton("匹配", this);

    m_logOutput = new QTextEdit(this);
    m_logOutput->setReadOnly(true);
    m_logOutput->setMinimumHeight(150);

    // 设置主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(5);
    mainLayout->setContentsMargins(5, 5, 5, 5);

    // 创建主选项卡
    QTabWidget *tabWidget = new QTabWidget(this);
    tabWidget->setMinimumWidth(250);

    // 设置整个 SettingsArea 的最小尺寸
    setMinimumSize(400, 400);

    // 设置所有按钮的最小宽度
    const int buttonMinWidth     = 50;
    QList<QPushButton *> buttons = findChildren<QPushButton *>();
    for (QPushButton *button : buttons)
    {
        button->setMinimumWidth(buttonMinWidth);
        button->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
    }

    // 调整布局的边距和间距
    mainLayout->setContentsMargins(5, 5, 5, 5);
    mainLayout->setSpacing(5);

    // 创建各个选项卡
    createBasicTab(tabWidget);
    createScanTab(tabWidget);
    createSearchTab(tabWidget);

    mainLayout->addWidget(tabWidget);

    // 创建日志区域
    createLogArea(mainLayout);

    m_updateFunctions.setLogOutput(m_logOutput);
}

void SettingsArea::createBasicTab(QTabWidget *tabWidget)
{
    QWidget *basicTab        = new QWidget();
    QVBoxLayout *basicLayout = new QVBoxLayout(basicTab);
    basicLayout->setSpacing(8);
    basicLayout->setContentsMargins(8, 8, 8, 8);

    basicLayout->addWidget(m_modifyPathButton);
    basicLayout->addWidget(m_settingsButton);
    basicLayout->addStretch();

    tabWidget->addTab(basicTab, "基础设置");
}

void SettingsArea::createScanTab(QTabWidget *tabWidget)
{
    QWidget *scanTab        = new QWidget();
    QVBoxLayout *scanLayout = new QVBoxLayout(scanTab);
    scanLayout->setSpacing(8);
    scanLayout->setContentsMargins(8, 8, 8, 8);

    // 扫描更新组
    QGroupBox *scanUpdateGroup    = new QGroupBox("扫描更新", scanTab);
    QVBoxLayout *scanUpdateLayout = new QVBoxLayout(scanUpdateGroup);
    scanUpdateLayout->setSpacing(5);

    scanUpdateLayout->addWidget(m_clearAndScanFolderButton);
    scanUpdateLayout->addWidget(m_appendScanFolderButton);
    scanUpdateLayout->addStretch();

    scanLayout->addWidget(scanUpdateGroup);

    // 重新生成组
    QGroupBox *regenerateGroup    = new QGroupBox("重新生成", scanTab);
    QVBoxLayout *regenerateLayout = new QVBoxLayout(regenerateGroup);
    regenerateLayout->setSpacing(5);

    QHBoxLayout *thresholdLayout      = new QHBoxLayout();
    QLabel *thresholdLabel            = new QLabel("人脸识别容差值:", regenerateGroup);
    m_faceRecognitionThresholdSpinBox = new QDoubleSpinBox(regenerateGroup);
    m_faceRecognitionThresholdSpinBox->setRange(0.1, 1.0);
    m_faceRecognitionThresholdSpinBox->setSingleStep(0.05);
    m_faceRecognitionThresholdSpinBox->setValue(0.5);
    m_faceRecognitionThresholdSpinBox->setToolTip("人脸识别的匹配阈值(0.1-1.0)\n"
                                                  "值越小匹配越严格，误识别率越低但可能漏识别\n"
                                                  "值越大匹配越宽松，漏识别率越低但可能误识别\n"
                                                  "建议值: 0.5");

    thresholdLayout->addWidget(thresholdLabel);
    thresholdLayout->addWidget(m_faceRecognitionThresholdSpinBox);
    thresholdLayout->addStretch();

    regenerateLayout->addWidget(m_rescanFolderButton);
    regenerateLayout->addLayout(thresholdLayout);
    regenerateLayout->addWidget(m_recognizeAllFacesButton);
    regenerateLayout->addWidget(m_recognizeFacesButton);
    regenerateLayout->addWidget(m_regenerateTypeButton);
    regenerateLayout->addWidget(m_regenerateDescriptionButton);
    regenerateLayout->addWidget(m_regenerateEmbeddingButton);
    regenerateLayout->addStretch();

    scanLayout->addWidget(regenerateGroup);
    scanLayout->addStretch();

    tabWidget->addTab(scanTab, "扫描与更新");
}

void SettingsArea::createSearchTab(QTabWidget *tabWidget)
{
    QWidget *searchTab        = new QWidget();
    QVBoxLayout *searchLayout = new QVBoxLayout(searchTab);
    searchLayout->setSpacing(5);

    QTabWidget *searchTabWidget = new QTabWidget(searchTab);
    searchLayout->addWidget(searchTabWidget);

    createContentSearchTab(searchTabWidget);
    createTypeSearchTab(searchTabWidget);
    createFaceSearchTab(searchTabWidget);
    createKeywordSearchTab(searchTabWidget);

    tabWidget->addTab(searchTab, "搜索功能");
}

void SettingsArea::createContentSearchTab(QTabWidget *searchTabWidget)
{
    QWidget *contentSearchTab        = new QWidget();
    QVBoxLayout *contentSearchLayout = new QVBoxLayout(contentSearchTab);
    contentSearchLayout->setSpacing(5);

    setupResultsCountArea(contentSearchLayout, contentSearchTab);
    setupContentSearchArea(contentSearchLayout, contentSearchTab);
    setupImageSearchArea(contentSearchLayout, contentSearchTab);

    searchTabWidget->addTab(contentSearchTab, "内容搜索");
}

void SettingsArea::createTypeSearchTab(QTabWidget *searchTabWidget)
{
    QWidget *typeSearchTab        = new QWidget();
    QVBoxLayout *typeSearchLayout = new QVBoxLayout(typeSearchTab);
    typeSearchLayout->setSpacing(5);

    QGroupBox *typeSearchBox         = new QGroupBox("类型搜索", typeSearchTab);
    QVBoxLayout *typeSearchBoxLayout = new QVBoxLayout(typeSearchBox);

    QHBoxLayout *typeSearchInputLayout = new QHBoxLayout();
    typeSearchInputLayout->addWidget(new QLabel("输入:", typeSearchTab));
    typeSearchInputLayout->addWidget(m_typeSearchInput, 1);
    typeSearchInputLayout->addWidget(m_typeSearchButton);
    typeSearchBoxLayout->addLayout(typeSearchInputLayout);

    QHBoxLayout *typeSelectLayout = new QHBoxLayout();
    typeSelectLayout->addWidget(new QLabel("选择:", typeSearchTab));
    typeSelectLayout->addWidget(m_typeSelectComboBox, 1);
    typeSelectLayout->addWidget(m_typeSelectButton);
    typeSearchBoxLayout->addLayout(typeSelectLayout);

    typeSearchLayout->addWidget(typeSearchBox);
    searchTabWidget->addTab(typeSearchTab, "类型搜索");
}

void SettingsArea::createFaceSearchTab(QTabWidget *searchTabWidget)
{
    QWidget *faceSearchTab = new QWidget();
    QVBoxLayout *faceSearchLayout = new QVBoxLayout(faceSearchTab);
    faceSearchLayout->setSpacing(5);

    QGroupBox *faceSearchBox = new QGroupBox("人脸搜索", faceSearchTab);
    QVBoxLayout *faceSearchBoxLayout = new QVBoxLayout(faceSearchBox);
    faceSearchBoxLayout->setSpacing(5);

    // 1. 输入搜索区域
    QHBoxLayout *faceSearchInputLayout = new QHBoxLayout();
    faceSearchInputLayout->addWidget(new QLabel("输入:", faceSearchTab));
    faceSearchInputLayout->addWidget(m_faceSearchInput, 1);
    faceSearchInputLayout->addWidget(m_faceSearchButton);
    faceSearchBoxLayout->addLayout(faceSearchInputLayout);

    // 2. 选择人脸区域 - 将所有控件放在同一行
    QHBoxLayout *faceSelectLayout = new QHBoxLayout();
    faceSelectLayout->addWidget(new QLabel("选择:", faceSearchTab));
    faceSelectLayout->addWidget(m_faceSelectComboBox, 1);
    faceSelectLayout->addWidget(m_refreshFaceListButton);
    faceSelectLayout->addWidget(m_faceSelectButton);
    faceSearchBoxLayout->addLayout(faceSelectLayout);

    // 3. 人脸预览区域 - 移到选择区域下方
    QGroupBox *previewGroup = new QGroupBox("人脸预览", faceSearchTab);
    QVBoxLayout *previewLayout = new QVBoxLayout(previewGroup);
    previewLayout->setContentsMargins(5, 5, 5, 5);

    m_facePreviewLabel = new QLabel(previewGroup);
    m_facePreviewLabel->setMinimumSize(100, 100);
    m_facePreviewLabel->setMaximumSize(200, 200);
    m_facePreviewLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    m_facePreviewLabel->setAlignment(Qt::AlignCenter);
    m_facePreviewLabel->setText("未选择人脸");
    m_facePreviewLabel->setStyleSheet(
        "QLabel { border: 1px solid #CCCCCC; background-color: #F5F5F5; }");

    previewLayout->addWidget(m_facePreviewLabel);
    previewLayout->setAlignment(m_facePreviewLabel, Qt::AlignCenter);
    
    faceSearchBoxLayout->addWidget(previewGroup);
    faceSearchBoxLayout->addStretch();

    // 添加到主布局
    faceSearchLayout->addWidget(faceSearchBox);
    searchTabWidget->addTab(faceSearchTab, "人脸搜索");
}

void SettingsArea::createKeywordSearchTab(QTabWidget *searchTabWidget)
{
    QWidget *keywordSearchTab        = new QWidget();
    QVBoxLayout *keywordSearchLayout = new QVBoxLayout(keywordSearchTab);
    keywordSearchLayout->setSpacing(5);

    QGroupBox *keywordSearchBox         = new QGroupBox("关键词搜索", keywordSearchTab);
    QHBoxLayout *keywordSearchBoxLayout = new QHBoxLayout(keywordSearchBox);
    keywordSearchBoxLayout->addWidget(new QLabel("关键词:", keywordSearchTab));
    keywordSearchBoxLayout->addWidget(m_keywordSearchInput, 1);
    keywordSearchBoxLayout->addWidget(m_keywordSearchButton);

    keywordSearchLayout->addWidget(keywordSearchBox);
    searchTabWidget->addTab(keywordSearchTab, "关键词搜索");
}

void SettingsArea::setupResultsCountArea(QVBoxLayout *contentSearchLayout, QWidget *parent)
{
    QHBoxLayout *resultsLayout = new QHBoxLayout();
    resultsLayout->addWidget(new QLabel("显示搜索结果数量:", parent));
    resultsLayout->addWidget(m_contentSearchResultsSpinBox);
    resultsLayout->addStretch();
    contentSearchLayout->addLayout(resultsLayout);
}

void SettingsArea::setupContentSearchArea(QVBoxLayout *contentSearchLayout, QWidget *parent)
{
    QGroupBox *contentSearchBox         = new QGroupBox("内容搜索", parent);
    QVBoxLayout *contentSearchBoxLayout = new QVBoxLayout(contentSearchBox);
    contentSearchBoxLayout->setSpacing(5);

    QHBoxLayout *contentSearchInputLayout = new QHBoxLayout();
    contentSearchInputLayout->addWidget(new QLabel("描述:", parent));
    contentSearchInputLayout->addWidget(m_contentSearchInput, 1);
    contentSearchInputLayout->addWidget(m_contentSearchButton);
    contentSearchBoxLayout->addLayout(contentSearchInputLayout);
    contentSearchLayout->addWidget(contentSearchBox);
}

void SettingsArea::setupImageSearchArea(QVBoxLayout *contentSearchLayout, QWidget *parent)
{
    QGroupBox *imageSearchBox      = new QGroupBox("以图搜图", parent);
    QVBoxLayout *imageSearchLayout = new QVBoxLayout(imageSearchBox);

    // 创建水平布局来放置预览图和按钮
    QHBoxLayout *imagePreviewLayout = new QHBoxLayout();

    // 创建一个容器widget来包含预览图片
    QWidget *previewContainer = new QWidget();
    previewContainer->setMinimumSize(100, 100);
    previewContainer->setMaximumSize(200, 200);
    QVBoxLayout *previewLayout = new QVBoxLayout(previewContainer);
    previewLayout->setContentsMargins(0, 0, 0, 0);
    previewLayout->addWidget(m_imagePreviewLabel);

    // 设置图片预览标签的属性
    m_imagePreviewLabel->setMinimumSize(100, 100);
    m_imagePreviewLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);

    // 添加预览容器到水平布局
    imagePreviewLayout->addWidget(previewContainer);

    // 创建垂直布局来放置按钮
    QVBoxLayout *buttonLayout = new QVBoxLayout();
    buttonLayout->addWidget(m_imageSearchSelectButton);
    buttonLayout->addWidget(m_imageSearchButton);
    buttonLayout->addStretch();

    // 将按钮布局添加到水平布局
    imagePreviewLayout->addLayout(buttonLayout);
    imagePreviewLayout->addStretch();

    // 将水平布局添加到图片搜索框的主布局
    imageSearchLayout->addLayout(imagePreviewLayout);

    // 添加到内容搜索选项卡的布局中
    contentSearchLayout->addWidget(imageSearchBox);
}

void SettingsArea::connectSignals()
{
    // 确保组件已初始化
    if (!m_faceSelectComboBox || !m_facePreviewLabel)
    {
        qDebug() << "Components not initialized in connectSignals";
        return;
    }

    // 断开之前的所有连接
    disconnect(m_faceSelectComboBox, nullptr, this, nullptr);

    // 重新建立连接
    connect(m_faceSelectComboBox, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
            this, &SettingsArea::updateFacePreview);

    connect(m_settingsButton, &QPushButton::clicked, this, &SettingsArea::openSettingsDialog);
    connect(m_clearAndScanFolderButton, &QPushButton::clicked, this,
            &SettingsArea::clearAndScanFolder);
    connect(m_appendScanFolderButton, &QPushButton::clicked, this, &SettingsArea::appendScanFolder);
    connect(m_contentSearchButton, &QPushButton::clicked, this, &SettingsArea::searchByContent);
    connect(m_typeSearchButton, &QPushButton::clicked, this, &SettingsArea::searchByType);
    connect(m_faceSearchButton, &QPushButton::clicked, this, &SettingsArea::searchByFace);
    connect(m_keywordSearchButton, &QPushButton::clicked, this, &SettingsArea::searchByKeywords);
    connect(m_modifyPathButton, &QPushButton::clicked, this, &SettingsArea::openPathSettingsDialog);

    connect(m_faceSelectComboBox, QOverload<int>::of(&QComboBox::activated), this,
            &SettingsArea::updateFaceList);
    connect(m_faceSelectButton, &QPushButton::clicked, this, &SettingsArea::searchSelectedFace);
    connect(m_typeSelectButton, &QPushButton::clicked, this, &SettingsArea::searchSelectedType);

    connect(m_recognizeFacesButton, &QPushButton::clicked, this, &SettingsArea::recognizeFaces);
    connect(m_regenerateTypeButton, &QPushButton::clicked, this, &SettingsArea::regenerateType);
    connect(m_regenerateDescriptionButton, &QPushButton::clicked, this,
            &SettingsArea::regenerateDescription);
    connect(m_regenerateEmbeddingButton, &QPushButton::clicked, this,
            &SettingsArea::regenerateEmbedding);

    connect(m_imageSearchSelectButton, &QPushButton::clicked, this,
            &SettingsArea::selectImageForSearch);
    connect(m_imageSearchButton, &QPushButton::clicked, this, &SettingsArea::searchByImage);
    connect(m_rescanFolderButton, &QPushButton::clicked, this, &SettingsArea::rescanFolder);
    connect(m_recognizeAllFacesButton, &QPushButton::clicked, this,
            &SettingsArea::recognizeAllFaces);

    connect(m_refreshFaceListButton, &QPushButton::clicked, this, &SettingsArea::updateFaceList);
}

void SettingsArea::log(const QString &message)
{
    m_logOutput->append(message);
    m_logOutput->verticalScrollBar()->setValue(m_logOutput->verticalScrollBar()->maximum());
    qDebug() << message;
}

bool SettingsArea::confirmAction(const QString &message)
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认操作", message, QMessageBox::Yes | QMessageBox::No);
    return reply == QMessageBox::Yes;
}

void SettingsArea::clearAndScanFolder()
{
    if (!confirmAction("更新会非常耗时，是否确认更新?"))
    {
        return;
    }

    m_logOutput->clear();

    QString folderPath    = m_pathSettings->getScanFolder();
    QString knownFacesDir = m_pathSettings->getKnownFacesDir();

    m_updateFunctions.clearAndScanFolder(folderPath, knownFacesDir, m_imageChatService, m_embedding,
                                         m_aiSettings);
    emit imageListUpdated(FileManager::getInstance().getFiles());
}

void SettingsArea::appendScanFolder()
{
    if (!confirmAction("更新会非常耗时，是否确认更新?"))
    {
        return;
    }

    m_logOutput->clear();

    QString folderPath    = m_pathSettings->getScanFolder();
    QString knownFacesDir = m_pathSettings->getKnownFacesDir();

    m_updateFunctions.appendScanFolder(folderPath, knownFacesDir, m_imageChatService, m_embedding,
                                       m_aiSettings);
    emit imageListUpdated(FileManager::getInstance().getFiles());
}

void SettingsArea::searchByContent()
{
    m_logOutput->clear();
    log("开始搜索文件内容详细描述...");

    QString query  = m_contentSearchInput->text();
    int numResults = m_contentSearchResultsSpinBox->value();

    QVector<float> queryEmbedding;

    // 检查是否可以使用缓存的查询向量
    if (query == m_lastContentQuery && !m_lastContentEmbedding.isEmpty())
    {
        log("使用缓存的查询向量...");
        queryEmbedding = m_lastContentEmbedding;
    }
    else
    {
        log("开始获取文件内容详细描述的嵌入向量...");
        queryEmbedding = m_embedding.getEmbedding(query, m_aiSettings.getEmbeddingAIUrl(),
                                                  m_aiSettings.getEmbeddingAIKey(),
                                                  m_aiSettings.getEmbeddingAIModel());

        // 缓存查询和向量
        m_lastContentQuery     = query;
        m_lastContentEmbedding = queryEmbedding;
    }

    log("开始计算相似度...");

    QList<QPair<float, FileInfo>> similarities;
    const QList<FileInfo> &files = FileManager::getInstance().getFiles();
    for (const FileInfo &file : files)
    {
        float similarity = Similarity::calculate(queryEmbedding, file.contentEmbedding);
        similarities.append(qMakePair(similarity, file));
    }

    std::sort(similarities.begin(), similarities.end(),
              [](const QPair<float, FileInfo> &a, const QPair<float, FileInfo> &b)
              { return a.first > b.first; });

    log(QString("开始获取相似度最高的前 %1 个文件...").arg(numResults));

    log("输出前9个匹配的文件信息");
    int count = 0;
    QVector<FileInfo> results;
    for (int i = 0; i < qMin(numResults, similarities.size()); ++i)
    {
        const FileInfo &file = similarities[i].second;
        results.append(file);
        if (count++ < 9)
        {
            log("\n相似度: " + QString::number(similarities[i].first * 100, 'f', 2) + "%" +
                "\n 文件名: " + file.fileName + "\n 人名: " + file.peopleNames.join(", ") +
                "\n 内容类型: " + file.contentType + "\n-------------\n");
        }
    }

    log("搜索完成");

    emit imageListUpdated(results);
}

void SettingsArea::searchByType()
{
    m_logOutput->clear();

    QString query = m_typeSearchInput->text();

    log("开始搜索文件内容类型...");

    QList<FileInfo> results = FileManager::getInstance().filterByContentType(query);

    log("共找到 " + QString::number(results.size()) + " 个匹配的文件");

    log("输出前9个匹配的文件信息");
    int count = 0;
    for (const FileInfo &file : results)
    {
        if (count++ < 9)
        {
            log("\n 文件名: " + file.fileName + "\n 人名: " + file.peopleNames.join(", ") +
                "\n 内容类型: " + file.contentType + "\n-------------\n");
        }
    }

    log("搜索完成");

    emit imageListUpdated(QVector<FileInfo>::fromList(results));
}

void SettingsArea::searchByFace()
{
    m_logOutput->clear();

    QString query = m_faceSearchInput->text();

    log("开始搜索人脸名称...");

    QList<FileInfo> results = FileManager::getInstance().filterByPerson(query);

    log("共找到 " + QString::number(results.size()) + " 个匹配的文件");

    log("输出前9个匹配的文件信息");
    int count = 0;
    for (const FileInfo &file : results)
    {
        if (count++ < 9)
        {
            log("\n 文件名: " + file.fileName + "\n 人名: " + file.peopleNames.join(", ") +
                "\n 容类型: " + file.contentType + "\n-------------\n");
        }
    }

    if (results.isEmpty())
    {
        log("没有找到匹配的文件");
    }
    else
    {
        log("共找到 " + QString::number(results.size()) + " 个匹配的文件");
    }

    log("搜索完成");

    emit imageListUpdated(QVector<FileInfo>::fromList(results));
}

void SettingsArea::searchByKeywords()
{
    m_logOutput->clear();

    QString input        = m_keywordSearchInput->text();
    QStringList keywords = input.split(" ", Qt::SkipEmptyParts);

    log("开始搜索文件内容详细描述关键字...");

    int count = 0;
    QVector<FileInfo> results;
    const QList<FileInfo> &files = FileManager::getInstance().getFiles();
    for (const FileInfo &file : files)
    {
        bool match = true;
        for (const QString &keyword : keywords)
        {
            if (!file.contentDescription.contains(keyword, Qt::CaseInsensitive))
            {
                match = false;
                break;
            }
        }
        if (match)
        {
            results.append(file);
            if (count++ < 9)
            {
                log("\n 文件名: " + file.fileName + "\n 人名: " + file.peopleNames.join(", ") +
                    "\n 内容类型: " + file.contentType + "\n-------------\n");
            }
        }
    }

    log("共找到 " + QString::number(results.size()) + " 个匹配的文件");

    log("搜索完成");

    emit imageListUpdated(results);
}

void SettingsArea::openSettingsDialog()
{
    m_aiSettings.openSettingsDialog();
}

void SettingsArea::openPathSettingsDialog()
{
    if (m_pathSettings->exec() == QDialog::Accepted)
    {
        // 如果需要，可以在这里更新其他相关组件
    }
}

void SettingsArea::updateFaceList()
{
    if (!m_faceSelectComboBox || !m_facePreviewLabel || !m_pathSettings)
    {
        qDebug() << "Essential components not initialized in updateFaceList";
        return;
    }

    QString currentFace = m_faceSelectComboBox->currentText();
    m_faceSelectComboBox->clear();

    QString knownFacesDir = m_pathSettings->getKnownFacesDir();
    if (knownFacesDir.isEmpty())
    {
        m_facePreviewLabel->setText("未设置人脸目录");
        return;
    }

    QDir dir(knownFacesDir);
    if (!dir.exists())
    {
        log("警告: 已知人脸目录不存在 - " + knownFacesDir);
        m_facePreviewLabel->setText("未找到人脸目录");
        return;
    }

    // 设置文件过滤器
    QStringList filters;
    filters << "*.png" << "*.jpg" << "*.jpeg";

    // 获取文件列表，只获取文件（不包括目录）
    QFileInfoList fileList = dir.entryInfoList(filters, QDir::Files | QDir::Readable, QDir::Name);

    // 检查是否有人脸图片文件
    if (fileList.isEmpty())
    {
        log("警告: 已知人脸目录中没有找到图片文件");
        m_facePreviewLabel->setText("未找到人脸图片");
        return;
    }

    // 收集有效的人脸名称
    QStringList faceNames;
    for (const QFileInfo &fileInfo : fileList)
    {
        // 检查文件是否可读
        if (!fileInfo.isReadable())
        {
            log("警告: 无法读取文件 - " + fileInfo.fileName());
            continue;
        }

        QString faceName = fileInfo.baseName();
        if (!faceName.isEmpty())
        {
            faceNames << faceName;
        }
    }

    // 检查是否有有效的人脸名称
    if (faceNames.isEmpty())
    {
        log("警告: 没有找到有效的人脸名称");
        m_facePreviewLabel->setText("未找到有效人脸");
        return;
    }

    // 对人脸名称进行排序
    faceNames.sort(Qt::CaseInsensitive);

    // 添加到下拉框
    m_faceSelectComboBox->addItems(faceNames);

    // 尝试恢复之前选中的人脸
    int index = m_faceSelectComboBox->findText(currentFace);
    if (index != -1)
    {
        m_faceSelectComboBox->setCurrentIndex(index);
    }
    // 如果没有找到之前选中的人脸，选择第一个项目
    else if (m_faceSelectComboBox->count() > 0)
    {
        m_faceSelectComboBox->setCurrentIndex(0);
        currentFace = m_faceSelectComboBox->currentText();
    }

    // 只有在有有效的人脸名称时才更新预览图
    if (!currentFace.isEmpty())
    {
        try
        {
            updateFacePreview(currentFace);
        }
        catch (...)
        {
            log("错误: 更新人脸预览图时发生异常");
            m_facePreviewLabel->setText("预览图加载失败");
        }
    }
}

void SettingsArea::searchSelectedFace()
{
    QString selectedFace = m_faceSelectComboBox->currentText();
    if (!selectedFace.isEmpty())
    {
        m_faceSearchInput->setText(selectedFace);
        searchByFace();
    }
}

void SettingsArea::searchSelectedType()
{
    QString selectedType = m_typeSelectComboBox->currentText();
    if (!selectedType.isEmpty())
    {
        m_typeSearchInput->setText(selectedType);
        searchByType();
    }
}

void SettingsArea::recognizeFaces()
{
    m_logOutput->clear();

    if (!confirmAction("重新识别人脸可能需要较长时间，是否继续?"))
    {
        return;
    }

    log("开始重新识别人脸...");

    QString knownFacesDir = m_pathSettings->getKnownFacesDir();
    QString folderPath    = m_pathSettings->getScanFolder();

    QString outputJsonPath = "face_recognition_results.json";
    double threshold       = m_faceRecognitionThresholdSpinBox->value();
    m_updateFunctions.recognizeFaces(false, knownFacesDir, folderPath, outputJsonPath, -1,
                                     threshold);
    m_updateFunctions.updateFaceInfo();
    emit imageListUpdated(FileManager::getInstance().getFiles());

    log("人脸识别完成");
}

void SettingsArea::regenerateType()
{
    m_logOutput->clear();

    if (!confirmAction("重新生成类型可能需要较长时间，是否继续?"))
    {
        return;
    }

    log("开始重新生成类型...");
    m_updateFunctions.updateContentType(m_imageChatService, m_aiSettings);
    FileManager::getInstance().saveToJson("file_info.json");
    emit imageListUpdated(FileManager::getInstance().getFiles());
    log("类型重新生成完成");
}

void SettingsArea::regenerateDescription()
{
    m_logOutput->clear();

    if (!confirmAction("重新生成描述可能需要较长时间，是否继续?"))
    {
        return;
    }

    log("开始重新生成描述...");
    m_updateFunctions.updateContentDescription(m_imageChatService, m_aiSettings);
    FileManager::getInstance().saveToJson("file_info.json");
    emit imageListUpdated(FileManager::getInstance().getFiles());
    log("描述重新生成完成");
}

void SettingsArea::regenerateEmbedding()
{
    m_logOutput->clear();

    if (!confirmAction("重新生成嵌入向量可能需要较长时间，是否继续?"))
    {
        return;
    }

    log("开始重新生成嵌入向量...");
    m_updateFunctions.updateEmbedding(m_embedding, m_aiSettings);
    FileManager::getInstance().saveToJson("file_info.json");
    emit imageListUpdated(FileManager::getInstance().getFiles());
    log("嵌入向量重新生成完成");
}

void SettingsArea::selectImageForSearch()
{
    QString filePath =
        QFileDialog::getOpenFileName(this, "选择图片", "", "图片文件 (*.png *.jpg *.jpeg)");
    if (!filePath.isEmpty())
    {
        m_selectedImagePath = filePath;
        // 清除缓存
        m_lastProcessedImagePath.clear();
        m_lastQueryEmbedding.clear();
        updateImagePreview(filePath);
    }
}

void SettingsArea::updateImagePreview(const QString &imagePath)
{
    QPixmap pixmap(imagePath);
    if (!pixmap.isNull())
    {
        // 缓存原始图片
        m_originalPreviewPixmap = pixmap;

        // 计算合适的预览大小
        QSize previewSize    = m_imagePreviewLabel->size();
        QPixmap scaledPixmap = m_originalPreviewPixmap.scaled(previewSize, Qt::KeepAspectRatio,
                                                              Qt::SmoothTransformation);
        m_imagePreviewLabel->setPixmap(scaledPixmap);
    }
    else
    {
        m_imagePreviewLabel->setText("无法加载图片");
    }
}

void SettingsArea::searchByImage()
{
    if (m_selectedImagePath.isEmpty())
    {
        QMessageBox::warning(this, "警告", "请先选一张图片");
        return;
    }

    m_logOutput->clear();
    log("开始以图搜图...");

    QVector<float> queryEmbedding;

    // 检查是否需要重新处理图片
    if (m_selectedImagePath != m_lastProcessedImagePath || m_lastQueryEmbedding.isEmpty())
    {
        queryEmbedding = m_updateFunctions.processImageForSearch(
            m_selectedImagePath, m_pathSettings->getKnownFacesDir(), m_imageChatService,
            m_embedding, m_aiSettings);

        if (queryEmbedding.isEmpty())
        {
            log("处理图片失败，请重试");
            return;
        }

        // 缓存处理结果
        m_lastProcessedImagePath = m_selectedImagePath;
        m_lastQueryEmbedding     = queryEmbedding;
    }
    else
    {
        log("使用缓存的图片处理结果...");
        queryEmbedding = m_lastQueryEmbedding;
    }

    log("开始计算相似度...");

    QList<QPair<float, FileInfo>> similarities;
    const QList<FileInfo> &files = FileManager::getInstance().getFiles();
    for (const FileInfo &file : files)
    {
        float similarity = Similarity::calculate(queryEmbedding, file.contentEmbedding);
        similarities.append(qMakePair(similarity, file));
    }

    std::sort(similarities.begin(), similarities.end(),
              [](const QPair<float, FileInfo> &a, const QPair<float, FileInfo> &b)
              { return a.first > b.first; });

    int numResults = m_contentSearchResultsSpinBox->value();
    log(QString("开始获取相似度最高的前 %1 文件...").arg(numResults));

    log("输出前9个匹配的文件信息");
    int count = 0;
    QVector<FileInfo> results;
    for (int i = 0; i < qMin(numResults, similarities.size()); ++i)
    {
        const FileInfo &file = similarities[i].second;
        results.append(file);
        if (count++ < 9)
        {
            log("\n相似度: " + QString::number(similarities[i].first * 100, 'f', 2) + "%" +
                "\n 文件名: " + file.fileName + "\n 人名: " + file.peopleNames.join(", ") +
                "\n 内容类型: " + file.contentType + "\n-------------\n");
        }
    }

    log("搜索完成");

    emit imageListUpdated(results);
}

void SettingsArea::createLogArea(QVBoxLayout *mainLayout)
{
    QGroupBox *logGroup    = new QGroupBox("操作日志", this);
    QVBoxLayout *logLayout = new QVBoxLayout(logGroup);
    logLayout->setContentsMargins(3, 3, 3, 3);
    logLayout->setSpacing(0);

    m_logOutput->setMinimumHeight(80);
    m_logOutput->setLineWrapMode(QTextEdit::WidgetWidth);
    m_logOutput->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_logOutput->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setWidget(m_logOutput);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_logOutput->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    logGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);

    logLayout->addWidget(scrollArea);
    mainLayout->addWidget(logGroup, 1);
}

void SettingsArea::rescanFolder()
{
    if (!confirmAction("重新扫描文件可能需要较长时间，是否继续?"))
    {
        return;
    }

    m_logOutput->clear();

    QString folderPath    = m_pathSettings->getScanFolder();
    QString knownFacesDir = m_pathSettings->getKnownFacesDir();

    m_updateFunctions.rescanFolder(folderPath, knownFacesDir, m_imageChatService, m_embedding,
                                   m_aiSettings);
    emit imageListUpdated(FileManager::getInstance().getFiles());
}

void SettingsArea::recognizeAllFaces()
{
    m_logOutput->clear();

    if (!confirmAction("识别所有人脸可能需要较长时间，是否继续?"))
    {
        return;
    }

    log("开始识别所有人脸...");

    QString knownFacesDir = m_pathSettings->getKnownFacesDir();
    QString folderPath    = m_pathSettings->getScanFolder();

    QString outputJsonPath = "face_recognition_results.json";
    double threshold       = m_faceRecognitionThresholdSpinBox->value();
    m_updateFunctions.recognizeFaces(true, knownFacesDir, folderPath, outputJsonPath, -1,
                                     threshold);
    m_updateFunctions.updateFaceInfo();
    emit imageListUpdated(FileManager::getInstance().getFiles());

    log("所有人脸识别完成");
}

void SettingsArea::updateFacePreview(const QString &faceName)
{
    if (!m_facePreviewLabel || !m_pathSettings)
    {
        qDebug() << "Essential components not initialized in updateFacePreview";
        return;
    }

    if (faceName.isEmpty())
    {
        m_facePreviewLabel->setText("未选择人脸");
        return;
    }

    QString knownFacesDir = m_pathSettings->getKnownFacesDir();
    if (knownFacesDir.isEmpty())
    {
        m_facePreviewLabel->setText("未设置人脸目录");
        return;
    }

    // 尝试加载不同格式的图片
    QStringList extensions = {".png", ".jpg", ".jpeg"};
    bool found             = false;

    for (const QString &ext : extensions)
    {
        QString imagePath = knownFacesDir + "/" + faceName + ext;
        QFileInfo fileInfo(imagePath);

        // 检查文件是否存在且可读
        if (fileInfo.exists() && fileInfo.isReadable())
        {
            QPixmap pixmap(imagePath);
            if (!pixmap.isNull())
            {
                // 保存原始图片
                m_originalFacePreviewPixmap = pixmap;
                
                // 获取标签的固定大小
                QSize labelSize = m_facePreviewLabel->minimumSize();
                
                // 根据固定大小缩放图片，保持宽高比
                QPixmap scaledPixmap = m_originalFacePreviewPixmap.scaled(
                    labelSize,
                    Qt::KeepAspectRatio,
                    Qt::SmoothTransformation
                );
                
                // 设置缩放后的图片
                m_facePreviewLabel->setPixmap(scaledPixmap);
                found = true;
                break;
            }
        }
    }

    if (!found)
    {
        m_facePreviewLabel->setText("无法加载人脸图片");
        log("警告: 无法加载人脸图片 - " + faceName);
    }
}
